//
//  YRRefresh.swift
//  YRResreshControl
//
//  Created by Viper on 16/7/1.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit
enum YRRefreshType : Int {
    //正常
    case Normal = 0
    //下啦中
    case Pulling = 1
    //刷新中
    case Refreshing = 2
}
let YRRefreshHeight : CGFloat = 50
class YRRefresh: UIControl {
    var scrollView : UIScrollView?
    var refreshState:YRRefreshType = .Normal{
        
        didSet{
            switch refreshState {
            case .Normal:
                messageLabeel.text = "正常"
                //如果上一个状态为刷新中执行动画
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: {
                        self.scrollView?.contentInset.top -= YRRefreshHeight
                    })
                    
                }
            case .Pulling:
                messageLabeel.text = "下拉中"
            case .Refreshing:
                messageLabeel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { 
                   self.scrollView?.contentInset.top += YRRefreshHeight
                    }, completion: { (_) in
                        //类似发送通知
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -YRRefreshHeight, width:SCREENW , height: YRRefreshHeight))
        
        setuoUI()
    }
    //MARK: - 供外界调用方法
    func endRefreshing(){
        
        refreshState = .Normal
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    //MARK: - 设置视图
    private func setuoUI(){
        
       backgroundColor = UIColor.orangeColor()
        
        addSubview(messageLabeel)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        messageLabeel.frame = CGRect(x: 0, y: 0, width: SCREENW, height: YRRefreshHeight)
        
    }
    //监听该类将要添加在哪个View上
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断是否有值 而且是否滚动
        guard let scrollView = newSuperview as? UIScrollView else{
            
            return
        }
        self.scrollView = scrollView
        /*
         1-被观察者
         2-观察者
         3-属性
         4-观察属性变化(old，new)
         */
        
        //注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
        
//        print(newSuperview)
    }
    //观察者中实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
 
        //contentOffset.y
        let cotentOffSetY = self.scrollView?.contentOffset.y
        let contentInsetTop = self.scrollView!.contentInset.top
        
//        print(cotentOffSetY)
//        print("\(contentInsetTop)----------------")
        
        //判断scrollView是否在拖动
        if scrollView!.dragging {
            
            if cotentOffSetY > -contentInsetTop - YRRefreshHeight && refreshState == .Pulling{
//                print("正常")
                refreshState = .Normal
            }else if cotentOffSetY <= -contentInsetTop - YRRefreshHeight && refreshState == .Normal{
//                print("下拉中")
                refreshState = .Pulling
            }
            
        }else{
            //用户松手 如果用户停止拖动 松手 而且控件的状态为下拉中
            if refreshState == .Pulling {
                
                refreshState = .Refreshing
            }
        }
    }
   //MARK: - 懒加载控件
    private lazy var messageLabeel : UILabel = {
       
        let lab = UILabel()
        lab.font = UIFont.systemFontOfSize(14)
        lab.textAlignment = .Center
        lab.textColor = UIColor.blackColor()
        lab.text = "正常"
        
        return lab
        
    }()
    
    deinit{
        
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        
    }
    
}
